package com.keepalive_kotlin.manager

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import com.blankj.utilcode.util.LogUtils
import com.keepalive_kotlin.activity.OnePixelActivity
import com.keepalive_kotlin.service.KeepAliveService
import com.keepalive_kotlin.utils.BatteryOptimizationUtil

/**
 * 保活管理器
 * 统一管理保活相关的功能
 */
class KeepAliveManager private constructor() {

    /**
     * 开始保活服务
     */
    fun startKeepAliveService(context: Context) {
        // 检查是否支持前台服务
        try {
            val intent = Intent(context, KeepAliveService::class.java)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
                LogUtils.i("$TAG 启动前台服务成功")
            } else {
                context.startService(intent)
                LogUtils.i("$TAG 启动服务成功")
            }
        } catch (e: Exception) {
            LogUtils.e("$TAG 启动服务失败: ${e.message}")
        }
    }

    /**
     * 停止保活服务
     */
    fun stopKeepAliveService(context: Context) {
        try {
            val intent = Intent(context, KeepAliveService::class.java)
            context.stopService(intent)
            LogUtils.i("$TAG 停止服务成功")
        } catch (e: Exception) {
            LogUtils.e("$TAG 停止服务失败: ${e.message}")
        }
    }

    /**
     * 启动1像素Activity
     */
    fun startOnePixelActivity(context: Context) {
        try {
            val intent = Intent(context, OnePixelActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
            context.startActivity(intent)
            LogUtils.i("$TAG 启动1像素Activity成功")
        } catch (e: Exception) {
            LogUtils.e("$TAG 启动1像素Activity失败: ${e.message}")
        }
    }

    /**
     * 检查并请求电池优化白名单
     */
    fun requestBatteryOptimizationWhitelist(activity: Activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!BatteryOptimizationUtil.isIgnoringBatteryOptimization(activity)) {
                // 使用我们自己的方法显示电池优化对话框
                BatteryOptimizationUtil.showBatteryOptimizationDialog(activity, null)
            }
        }
    }

    companion object {
        private const val TAG = "KeepAliveManager"
        
        @Volatile
        private var instance: KeepAliveManager? = null

        fun getInstance(): KeepAliveManager {
            return instance ?: synchronized(this) {
                instance ?: KeepAliveManager().also { instance = it }
            }
        }
    }
}